package com.huishu.commons.utlis;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.GeneralSecurityException;
import java.util.*;

public class HttpUtils {

    private static final String CONTENT_TYPE_URL_ENCODE = "application/x-www-form-urlencoded;charset=utf-8";

    private static final String CONTENT_TYPE_JSON_ENCODE = "application/json;charset=utf-8";

    private static Random random = null;

    private static List<String> exploreList = null;

    private static Logger LOGGER = LoggerFactory.getLogger(HttpUtils.class);

    /**
     * get 请求
     *
     * @param url
     * @return
     * @throws IOException
     * @throws GeneralSecurityException
     */
    public static JSONObject doGet(String url, String authorization) {
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        GetMethod getMethod = new GetMethod(url);
        getMethod.addRequestHeader("accept", "*/*");

        getMethod.addRequestHeader("User-Agent", getUA());

        if (StringUtils.isNotBlank(authorization)) {
            getMethod.addRequestHeader("Authorization", authorization);
        }

        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理，用的是默认的重试处理：请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());


        String response = "";
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("请求出错HTTP Status： {}", getMethod.getStatusLine());
            }
            //读取HTTP响应内容，这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, "UTF-8");
            LOGGER.info("请求返回值： {}", response);
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            getMethod.releaseConnection();
        }
        return JSONObject.parseObject(response);
    }

    /**
     * get 请求
     *
     * */
    public static JSONObject doGet(String url, Map<String, Object> maps) {
        String urlParams = asUrlParams(maps);
        if (urlParams != null) {
            url = url + "?" + urlParams;
        }
        return doGet(url, "");
    }

    /**
     * get 请求
     *
     * */
    public static JSONObject doGet(String url, String authorization, Map<String, Object> maps) {
        String urlParams = asUrlParams(maps);
        if (urlParams != null) {
            url = url + "?" + urlParams;
        }
        return doGet(url, authorization);
    }

    /**
     * 只要确保你的编码输入是正确的,就可以忽略掉 UnsupportedEncodingException
     */
    public static String asUrlParams(Map<String, Object> source) {
        if (source.isEmpty()) {
            return null;
        }
        Iterator<String> it = source.keySet().iterator();
        StringBuilder paramStr = new StringBuilder();
        while (it.hasNext()) {
            String key = it.next();
            Object value = source.get(key);
            if (value == null) {
                continue;
            }
            try {
                // URL 编码
                value = URLEncoder.encode(value.toString(), "utf-8");
            } catch (UnsupportedEncodingException e) {
                LOGGER.error("http url 编码异常:{}", e.getMessage());
            }
            paramStr.append("&").append(key).append("=").append(value);
        }
        // 去掉第一个&
        return paramStr.substring(1);
    }

    /**
     * post请求
     *
     * @param url
     * @param paramJson
     * @return
     */
    public static JSONObject doJsonPost(String url, String paramJson, String authorization) throws IOException {
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.getName();
        postMethod.addRequestHeader("accept", "*/*");

        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送 CONTENT_TYPE_JSON_ENCODE
        postMethod.addRequestHeader("Content-Type", "application/json");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", getUA());
        if (StringUtils.isNotBlank(authorization)) {
            postMethod.addRequestHeader("Authorization", authorization);
        }

        RequestEntity entity = new StringRequestEntity(paramJson, CONTENT_TYPE_JSON_ENCODE, "UTF-8");
        postMethod.setRequestEntity(entity);
        String response = "";
        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;
        try {
            LOGGER.info("请求值： {}", JSON.toJSONString(postMethod.getRequestEntity()));
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("请求出错HTTP Status： {}", postMethod.getStatusLine());
            }
            inputStreamReader = new InputStreamReader(postMethod.getResponseBodyAsStream());
            reader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String readLine;
            while ((readLine = reader.readLine()) != null) {
                stringBuffer.append(readLine);
            }
            response = stringBuffer.toString();
            LOGGER.info("请求返回值： {}", response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            postMethod.releaseConnection();
        }
        return JSONObject.parseObject(response);
    }

    public static JSONObject doFormPost(String url, String paramJson) throws IOException {
        LOGGER.info("请求值： {}", paramJson);
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
        postMethod.getName();
        postMethod.addRequestHeader("accept", "*/*");

        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", CONTENT_TYPE_URL_ENCODE);
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", getUA());

        RequestEntity entity = new StringRequestEntity(paramJson, CONTENT_TYPE_URL_ENCODE, "UTF-8");
        postMethod.setRequestEntity(entity);
        String response = "";
        BufferedReader reader = null;
        InputStreamReader inputStreamReader = null;
        try {
            int statusCode = httpClient.executeMethod(postMethod);
            if (statusCode != HttpStatus.SC_OK) {
                LOGGER.error("请求出错HTTP Status： {}", postMethod.getStatusLine());
            }
            inputStreamReader = new InputStreamReader(postMethod.getResponseBodyAsStream());
            reader = new BufferedReader(inputStreamReader);
            StringBuffer stringBuffer = new StringBuffer();
            String readLine;
            while ((readLine = reader.readLine()) != null) {
                stringBuffer.append(readLine);
            }
            response = stringBuffer.toString();
            LOGGER.info("请求返回值： {}", response);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            postMethod.releaseConnection();
        }
        return JSONObject.parseObject(response);
    }



    private static String getUA() {
        if (null == exploreList) {
            exploreList = new ArrayList<>();
            exploreList.add("Chrome");
            exploreList.add("Mozilla");
            exploreList.add("Safari");
            exploreList.add("Firefox");
        }
        int version = getRandom(2, 9);
        int index = getRandom(0, exploreList.size() - 1);
        String uaStr = exploreList.get(index) + "/" + version + ".0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)";
        return uaStr;
    }

    private static int getRandom(int min, int max) {
        if (null == random) {
            random = new Random();
        }
        return random.nextInt(max) % (max - min + 1) + min;
    }


    public static void main(String[] args) throws IOException, GeneralSecurityException {
//        String url = "http://a1.easemob.com/1113210319091334/gongpaipai/token";
//        String paramJson = "{\n" +
//                "    \"grant_type\":\"client_credentials\",\n" +
//                "    \"client_id\":\"YXA6nt7JqzpzTgOSaO2apjC7Iw\",\n" +
//                "    \"client_secret\":\"YXA6D5Iazlxwat6Avdnx0QU_3EjxsB8\"\n" +
//                "}";
//        String registerJson = "{\n" +
//                "    \"username\":\"1234787345325228032\",\n" +
//                "    \"password\":\"7f1880b50988a463b7aa410c4c133568\",\n" +
//                "    \"nickname\":\"纯洁的微笑\"\n" +
//                "}";
//        String registerUrl = "http://a1.easemob.com/1113210319091334/gongpaipai/users";
////        doJsonPost(registerUrl, registerJson, null);
//        System.out.println(DigestUtils.md5Hex("gxfc@gongpaipai.com"));

        String statusUrl = "http://a1.easemob.com/1113210319091334/gongpaipai/users/batch/status";
        String authorization = "Bearer YWMtQ_r03oksEeuYAatrNs9R6QAAAAAAAAAAAAAAAAAAAAGe3smrOnNOA5Jo7ZqmMLsjAgMAAAF4TazdBQBPGgBpQ78xeRaimHHcDvIpEYzbrFt6mB6_CyHr5eRn7lqBaw";
        List<String> usernames = Arrays.asList("1234787345325228032", "454885451", "77777777");
        JSONObject object = new JSONObject();
        object.put("usernames", usernames);

        JSONObject jsonObject = doJsonPost(statusUrl, object.toJSONString(), authorization);
        JSONArray jsonArray = jsonObject.getJSONArray("data");
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject user = jsonArray.getJSONObject(i);
            for (Map.Entry maps : user.entrySet()) {
                System.out.println(maps.getKey());
                System.out.println(maps.getValue());
            }
        }

    }

}
